package com.xb.controller;

import com.alibaba.fastjson.JSON;
import com.xb.entity.User;
import com.xb.utils.XBHashMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class BaseController extends HttpServlet {
    public User loginUser;
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        try {

            HttpSession session = req.getSession();
            loginUser = (User) session.getAttribute("loginUser");

            String requestURI = req.getRequestURI();

            String targetName = requestURI.substring(requestURI.lastIndexOf("/") + 1);

            Class<? extends BaseController> aClass = this.getClass();

            Method method=aClass.getDeclaredMethod(targetName, HttpServletRequest.class, HttpServletResponse.class);
            method.setAccessible(true);
            method.invoke(this,req,resp);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 获取request中的键值对，返回Map<String,String>
     *
     * @param request
     * @return
     */
    public static Map<String, String> getParam(HttpServletRequest request) {

        Map<String, String> returnMap = new XBHashMap();

        // request中封装的前端的值
        Map<String,String[]> parameterMap = request.getParameterMap();

        for (String key : parameterMap.keySet()) {

            String[] values = parameterMap.get(key);
            // 真的提交了多值(多选框)
            if (values.length > 1) {

                // 使用逗号拼接字符串 [3,4,5,6,7]
                String val = Arrays.toString(values);

                returnMap.put(key, val);
            } else {
                //只要第0个下标的值
                returnMap.put(key, values[0]);
            }
        }

        return returnMap;
    }


    /**
     * 将数据以json方式写到前端
     * @param response
     * @param object
     * @return
     */
    public void writerObjToString(HttpServletResponse response,Object object) {
        try {
            String jsonStr = JSON.toJSONString(object);

            response.setContentType("application/json;charset=utf8");

            response.getWriter().write(jsonStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



}
